<uieip type="page" value="base"></uieip>
<uieip type="reg" value="login,session,console"></uieip>
<!doctype html>
<html>

<head>
    <uieip type="file" value="inc" src="/jsvm/inc/head.html"></uieip>
    <title>登录</title>
</head>

<body>
    <uieip type="file" value="exec" src="/jsvm/inc/title_exec.html"></uieip>
    <div class="container">
        <div class="row" style="margin-top:100px">
            <div class="col-md-offset-2 col-md-4 col-sm-6" style="padding: 5px;">
                <div class="panel panel-default">
                    <div class="panel-heading">微信扫码登录</div>
                    <div id="login_container"></div>
                </div>
            </div>
            <div class="col-md-4 col-md-5 col-sm-6" style="padding: 5px;">
                <div class="panel panel-default">
                    <div class="panel-heading">用户登录</div>
                    <div class="panel-body">
                        <label for="txt_loginName">登录名</label>
                        <input type="text" class="form-control" id="txt_loginName" placeholder="登录名">
                        <label for="txt_passwd">密码</label>
                        <input type="password" class="form-control" id="txt_passwd" placeholder="密码">
                        <label id="lbl_checkcode" for="txt_checkcode">掩码</label>
                        <img src="/login/`checkcode.png" id="img_checkcode" style="height: 25px;"></img>
                        <input type="text" class="form-control" id="txt_checkcode" placeholder="掩码">
                        <p></p>
                        <button id="btn_login" type="button" class="btn btn-primary pull-right">登录</button>
                        <a class="a_third_verif" href="javascript:third_verif();">手机|邮箱登录</a>
                        <a class="a_weixin" href="javascript:third_login('weixin');">微信登录</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <uieip type="file" value="inc" src="/jsvm/inc/foot.html"></uieip>
    <!-- 密码学计算库 -->
    <script src="/scripts/crypto/sha256.min.js"></script>
    <script src="js/login.js"></script>
    <script src="http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>
    <script>
        // Cookie 操作封装
        const Cookie = {
            get: function (name) {
                return parseInt(document.cookie.replace(new RegExp(`(?:(?:^|.*;\s*)${name}\s*\=\s*([^;]*).*$)|^.*$`), "$1")) || 0;
            },
            set: function (name, value, expires) {
                document.cookie = `${name}=${value}; path=/; expires=${expires}`;
            },
            remove: function (name) {
                this.set(name, "0", "Thu, 01 Jan 1970 00:00:00 GMT");
            }
        };

        $(function () {
            const $loginForm = {
                username: $("#txt_loginName"),
                password: $("#txt_passwd"),
                checkcode: $("#txt_checkcode"),
                checkcodeLabel: $("#lbl_checkcode"),
                checkcodeImage: $("#img_checkcode"),
                loginBtn: $("#btn_login")
            };

            // 初始化验证码显示
            showCheckcode();

            // 绑定回车事件
            //$loginForm.username.keydown(e => e.keyCode === 13 && $loginForm.password.focus());
            //$loginForm.password.keydown(e => e.keyCode === 13 && $loginForm.loginBtn.click());

            // 登录按钮点击事件
            $loginForm.loginBtn.on("click", function () {
                const loginData = {
                    loginName: $loginForm.username.val(),
                    passwd: $loginForm.password.val(),
                    captcha: ""
                };

                if ($loginForm.checkcode.is(":visible") && $loginForm.checkcode.val()) {
                    loginData.mask = $loginForm.checkcode.val();
                }

                $.login(loginData, handleLoginResponse);
            });

            // 处理登录响应
            function handleLoginResponse(res) {
                console.log(res);
                if (res.error === 0) {
                    Cookie.remove("login_error_count");
                    console.log("res", res);
                    if (res.verif) {
                        window.location.href = "/login/login_verif.html?backurl=" + encodeURIComponent(backurl_get()) + "&verif=1";
                    } else {
                        if (res.uppw) {
                            window.location.href = "/login/index.html?backurl=" + encodeURIComponent(backurl_get());
                        } else {
                            window.location.href = backurl_get();
                        }
                    }
                    return;
                }

                const errorCount = Cookie.get("login_error_count") + 1;
                const expires = new Date(Date.now() + 24 * 60 * 60 * 1000).toUTCString();
                Cookie.set("login_error_count", errorCount, expires);

                showCheckcode();
                alert(`${res.info}[${res.error}] 错误次数:${errorCount}`);
            }

            // 显示/隐藏验证码
            function showCheckcode() {
                if (!$loginForm.checkcode.length) return;

                const errorCount = Cookie.get("login_error_count");
                const show = errorCount >= 3;

                $loginForm.checkcodeLabel.toggle(show);
                $loginForm.checkcode.toggle(show);
                $loginForm.checkcodeImage.toggle(show);

                if (show) {
                    $loginForm.checkcode.val("");
                    $loginForm.checkcodeImage.attr("src", `/login/\`checkcode.png?t=${Date.now()}`);
                }
            }

            $loginForm.username.focus();
            $loginForm.username.keydown(function (e) {
                if (e.keyCode === 13) {
                    $loginForm.password.focus();
                }
            });
            $loginForm.password.keydown(function (e) {
                if (e.keyCode === 13) {
                    // 检查验证码是否可见
                    if (!$loginForm.checkcode.is(":visible")) {
                        $loginForm.loginBtn.click();
                    } else {
                        // 如果验证码可见，可以在这里添加其他逻辑，比如聚焦到验证码输入框
                        $loginForm.checkcode.focus();
                    }
                }
            });
            $loginForm.checkcode.keydown(function (e) {
                if (e.keyCode === 13) {
                    $loginForm.loginBtn.click();
                }
            });
        });

        // 第三方登录相关
        function third_login(link_type) {
            window.location.href = "/login/login_third.html?backurl=" + encodeURIComponent(backurl_get());
        }

        //手机|邮箱登录
        function third_verif() {
            window.location.href = "/login/login_verif.html?backurl=" + encodeURIComponent(backurl_get());
        }

        function backurl_get() {
            return $.urlRequest("backurl") || "/index.html";
        }

        // 微信登录初始化
        new WxLogin({
            self_redirect: false,
            id: "login_container",
            appid: "<uieip>wx_appid</uieip>",
            scope: "snsapi_login",
            redirect_uri: encodeURIComponent("<uieip>wx_redirect_uri</uieip>"),
            state: "<uieip>wx_state</uieip>",
            style: "white",
            href: "",
            stylelite: 1
        });
    </script>
    <script runat="server">
        let wx_appid, wx_redirect_uri, wx_state;
        function init() {
            // 处理回调URL
            const backurl = request.param("backurl");
            var lg_state = login.state();
            if (lg_state) {
                if (backurl === null) {
                    response.redirect("/index.html");
                }
                else {
                    response.redirect(backurl);
                }
                return;
            }

            if (!(backurl === null)) {
                session.set("backurl", backurl);
            }
            // 初始化微信登录参数
            wx_redirect_uri = `${request.baseurl()}/login/login_third.html`;
            const wxParams = login.third_params("weixin", "state");

            if (wxParams.error === 0) {
                wx_appid = wxParams.appid;
                wx_state = wxParams.state;
            }
        }
        init();
    </script>
</body>

</html>